//
//  MYReplenishmentRecordViewController.m
//  MiYuan_iOS
//
//  Created by zhangyongbing on 2018/5/16.
//  Copyright © 2018年 zhangyongbing. All rights reserved.
//

#import "MYReplenishmentRecordViewController.h"
#import "ReplenishmentRecordTableCell.h"
#import "EGORefreshTableHeaderView.h"
#import "EGORefreshTableFootView.h"
#import "MYPersonal_HttpAPI.h"

@interface MYReplenishmentRecordViewController ()<UIGestureRecognizerDelegate,EGORefreshTableHeaderDelegate,EGORefreshTableFootDelegate>
{
    BOOL isShowChoose;
    BOOL isReload;
    NSInteger  startpage;
    CGPoint point;//判断是上拉还是下拉
    BOOL reloading;
    
    EGORefreshTableHeaderView *egoRefreshTableHeaderView;
    EGORefreshTableFootView *_refreshFootView;
}
@property (nonatomic,copy) NSString  *time;
@property (nonatomic,weak) IBOutlet   UITextField     *fieldSearch;
@property (nonatomic,weak) IBOutlet   UIView      *viewDate;
@property (nonatomic,weak) IBOutlet   UITableView     *tabMain;
@property (nonatomic,weak) IBOutlet   UIDatePicker    *datepick;
@property (nonatomic,weak) IBOutlet   UILabel         *labTime;
@property (nonatomic,weak) IBOutlet   UIImageView     *imgFieldBg;
@property (nonatomic,strong) NSMutableArray  *arrayData;
@property (nonatomic,weak) IBOutlet   UIView          *viewHead;

@end

@implementation MYReplenishmentRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSString *version= [UIDevice currentDevice].systemVersion;
    
    if(version.doubleValue >=11.0) {
        
    }else{
        // 针对 11.0 以下的iOS系统进行处理
        for (NSLayoutConstraint *constraint in self.viewHead.superview.constraints) {
            if (constraint.firstItem == self.viewHead && constraint.firstAttribute == NSLayoutAttributeTop) {
                constraint.constant = 20;
            }
        }
        
    }
    isShowChoose = NO;
    startpage = 0;
    isReload = NO;
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    self.time = [formatter stringFromDate:date];
    [self.labTime setText:self.time];
    
    [self.imgFieldBg.layer setMasksToBounds:YES];
    [self.imgFieldBg.layer setCornerRadius:6]; //设置矩形四个圆角半径
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignRespond)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    [self getDataFromServices];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)resignRespond
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    if (isShowChoose) {
        [self onShowOrHiddenChooseView];
    }
}

- (void)onCreateEgoHeadView
{
    //    下拉刷新
    if (egoRefreshTableHeaderView == nil) {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tabMain.bounds.size.height, self.view.frame.size.width, self.tabMain.bounds.size.height)];
        view.delegate = self;
        egoRefreshTableHeaderView = view;
        egoRefreshTableHeaderView.backgroundColor = [UIColor colorWSHHFromHexString:@"F1F1F1"];
        [self.tabMain addSubview:view];
    }
    //  update the last update date
    [egoRefreshTableHeaderView refreshLastUpdatedDate];
}

-(void) addMoreView{
    if (_refreshFootView == nil) {
        _refreshFootView = [[EGORefreshTableFootView alloc] initWithFrame: CGRectMake(0.0f, self.tabMain.contentSize.height, WINDOWWIDTH, 650)];
        _refreshFootView.delegate = self;
        _refreshFootView.backgroundColor = [UIColor lightGrayColor];
        [self.tabMain addSubview:_refreshFootView];
        _refreshFootView.hidden = YES;
    }
    
}
-(void) modifyMoreFrame{
    _refreshFootView.frame = CGRectMake(0.0f, self.tabMain.contentSize.height, WINDOWWIDTH, 650);
}

#pragma mark - Http
- (void)getDataFromServices
{
    NSString *string = self.fieldSearch.text;
    if (![string stringIsValid]) {
        string = @"";
    }
    [MYPersonal_HttpAPI myMyReplenushmentListWithparameter:string Time:self.time PageNum:[NSString stringWithFormat:@"%ld",(long)startpage] PageSize:@"20" complationHandler:^(OCJBaseResponceModel *responseModel) {
        [self performSelectorOnMainThread:@selector(doneLoadingTableViewData) withObject:self waitUntilDone:NO];
        startpage ++;
        id packageList = [responseModel.ocjDic_data objectForKey:@"records"];
        if (packageList && [packageList isKindOfClass:[NSArray class]]) {
            if (isReload) {
                [self.arrayData removeAllObjects];
                for (id package in packageList) {
                    if (package && [package isKindOfClass:[NSDictionary class]]) {
                        [self.arrayData addObject:package];
                    }
                }
            }
            else
            {
                for (id package in packageList) {
                    if (package && [package isKindOfClass:[NSDictionary class]]) {
                        [self.arrayData addObject:package];
                    }
                }
            }
            if ([(NSArray *)packageList count] < 10) {
                [_refreshFootView setHidden:YES];
            }
            else
            {
                [_refreshFootView setHidden:NO];
            }
            
        }
        [self.tabMain reloadData];
    }];
    
}

- (IBAction)onBackButtonPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onCHooseDateSureButtonPressed:(id)sender
{
    NSDate *date = self.datepick.date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    self.time = [formatter stringFromDate:date];
    [self.labTime setText:self.time];
    [self onShowOrHiddenChooseView];
    startpage = 0;
    isReload = YES;
    [self getDataFromServices];
}

- (IBAction)onCHooseDateCancelButtonPressed:(id)sender
{
    [self onShowOrHiddenChooseView];
}

- (void)onShowOrHiddenChooseView
{
    if (isShowChoose) {
        [self replacePickerContainerViewBottomConstraintWithConstant:500];
        CGRect bounds = self.view.bounds;
        bounds.origin.y = 0;
        [UIView animateWithDuration:0.5 animations:^{
            self.view.bounds = bounds;
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            isShowChoose = NO;
        }];
    }
    else
    {
        CGRect bounds = self.view.bounds;
        
        [self replacePickerContainerViewBottomConstraintWithConstant:0];
        [UIView animateWithDuration:0.5 animations:^{
            self.view.bounds = bounds;
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            isShowChoose = YES;
        }];
    }
}

- (void)replacePickerContainerViewBottomConstraintWithConstant:(CGFloat)constant
{
    for (NSLayoutConstraint *constraint in self.viewDate.superview.constraints) {
        if (constraint.firstItem == self.viewDate && constraint.firstAttribute == NSLayoutAttributeBottom) {
            constraint.constant = constant;
        }
    }
}

- (IBAction)onChooseDateButtonPressed:(id)sender
{
    [self onShowOrHiddenChooseView];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.fieldSearch resignFirstResponder];
    isReload = YES;
    startpage = 0;
    [self getDataFromServices];
    return YES;
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[UIButton class]])
    {
        return NO;
    }
    if ([NSStringFromClass([touch.view class])isEqual:@"UITableViewCellContentView"])
    {
        return NO;
    }
    return YES;
}

#pragma mark - tableViewDelegate
#pragma mark - tableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self modifyMoreFrame];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CGFloat height = 55;
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifiernoe = @"ReplenishmentRecordTableCell";
    ReplenishmentRecordTableCell *cell  = (ReplenishmentRecordTableCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifiernoe];
    
    if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"ReplenishmentRecordTableCell" bundle:nil] forCellReuseIdentifier:cellIdentifiernoe];
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifiernoe];
    }
    NSDictionary *dic = [self.arrayData objectAtIndex:indexPath.row];
    [cell setDataToViewWithDictionary:dic];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self resignRespond];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    point =scrollView.contentOffset;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //    [egoRefreshTableHeaderView egoRefreshScrollViewDidScroll:scrollView];
    CGPoint pt =scrollView.contentOffset;
    if (point.y < pt.y) {//向上提加载更多
        if (_refreshFootView.hidden) {
            return;
        }
        [_refreshFootView egoRefreshScrollViewDidScroll:scrollView];
    }
    else {
        [egoRefreshTableHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //    [egoRefreshTableHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    CGPoint pt =scrollView.contentOffset;
    if (point.y < pt.y) {//向上提加载更多
        if (_refreshFootView.hidden) {
            return;
        }
        [_refreshFootView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    else {//向下拉加载更多
        [egoRefreshTableHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}
#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    isReload = YES;
    startpage = 0;
    [self getDataFromServices];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
    
    return [NSDate date]; // should return date data source was last changed
    
}

#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableFootDidTriggerRefresh:(EGORefreshTableFootView*)view{
    isReload = NO;
    [self getDataFromServices];
    
}

- (BOOL)egoRefreshTableFootDataSourceIsLoading:(EGORefreshTableFootView*)view{
    
    return reloading; // should return if data source model is reloading
}


#pragma mark -
#pragma mark Data Sources Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    reloading = YES;
    
}

- (void)doneLoadingTableViewData{
    
    
    //  model should call this when its done loading
    reloading = NO;
    [egoRefreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tabMain];
    [_refreshFootView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tabMain];
    
}

#pragma mark - UIDatePicker

- (IBAction)ondateChange:(id)sender
{
    UIDatePicker *date = (UIDatePicker *)sender;
    NSLog(@"%@", date.date);
}

- (NSMutableArray *)arrayData
{
    if (_arrayData == nil) {
        _arrayData = [[NSMutableArray alloc] init];
    }
    return _arrayData;
}

@end
